package com.example.fdfs.demo.controller;


import com.example.fdfs.demo.utils.FastDFSClient;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/fdfs")
@EnableSwagger2
public class FastDFSController {


    @Autowired
    private FastDFSClient fdfsClient;

    @RequestMapping(value="/uploadPage",method = RequestMethod.GET)
    public ModelAndView uploadPage(ModelAndView mv) throws Exception {
        mv.addObject("title", "upload page");
        mv.setViewName("file");
        return mv;
    }

    /**
     * 文件上传
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/upload")
    @ApiOperation(value = "文件上传", notes="文件上传")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "文件上传", required = true, dataType = "MultipartFile")})
    public Map<String,Object> upload(MultipartFile file) throws Exception{

        String url = fdfsClient.uploadFile(file);

        Map<String,Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "上传成功");
        result.put("url", url);

        return result;
    }

    /**
     * 文件下载
     * @param fileUrl  url 开头从组名开始
     * @param response
     * @throws Exception
     */
    @RequestMapping("/download")
    @ApiOperation(value = "文件下载", notes="文件下载")
    @ApiImplicitParams({@ApiImplicitParam(name = "fileUrl", value = "文件下载路径", required = true, dataType = "String"),
            @ApiImplicitParam(name = "response", value = "response", required = false, dataType = "HttpServletResponse")})
    public void  download(String fileUrl, HttpServletResponse response) throws Exception{

        byte[] data = fdfsClient.download(fileUrl);

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("test.jpg", "UTF-8"));

        // 写出
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.write(data, outputStream);
    }



}
